package leecode

func countSubIslands(grid1 [][]int, grid2 [][]int) int {
	var dfs func(grid1, grid2 [][]int, row, column int)
	var flag bool
	dfs = func(grid1, grid2 [][]int, row, column int) {
		if !isArea1905(grid2, row, column) {
			return
		}
		if grid2[row][column] != 1 {
			return
		}
		//遍历过的岛屿 , 标记为2
		grid2[row][column] = 2
		if grid1[row][column] == 0 {
			flag = false
		}
		dfs(grid1, grid2, row-1, column)
		dfs(grid1, grid2, row+1, column)
		dfs(grid1, grid2, row, column-1)
		dfs(grid1, grid2, row, column+1)
	}
	var result int
	for i := 0; i < len(grid2); i++ {
		for j := 0; j < len(grid2[i]); j++ {
			//遍历岛屿2 , 只要在岛屿1相应位置上是水 , 就不是子岛屿
			if grid2[i][j] == 1 {
				flag = true
				dfs(grid1, grid2, i, j)
				//符合条件
				if flag {
					result++
				}
			}
		}
	}
	return result
}

func isArea1905(grid2 [][]int, row, column int) bool {
	return 0 <= row && row < len(grid2) && 0 <= column && column < len(grid2[0])
}
